package com.tools.web.filter.gateway;

import com.tools.common.object.Note;
import com.tools.common.thread.Timeunit;
import com.tools.db.cache.expiring.ExpiringMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 使用过期 Map 集合实现的网管过滤器
 * */
@Note("使用过期 Map 集合实现的网管过滤器")
public final class ExpiringMapGetawayFilter extends AbsLocalCacheGetawayFilter {

    @Note("过期 Map 集合实现的本地缓存")
    private final ExpiringMap<String, Object> cache;

    @Note("日志输出实例")
    private static final Logger LOGGER = LoggerFactory.getLogger(ExpiringMapGetawayFilter.class);

    public ExpiringMapGetawayFilter(ExpiringMap<String, Object> cache, GetawaySource source) {
        super(source, cache != null, "本地缓存实例不能为 null");
        this.cache = cache;
    }

    @Override
    protected Logger protected_getLogger() {
        return LOGGER;
    }

    @Override
    protected Timeunit protected_getImplSelfTimeunit() {
        return Timeunit.MILL;
    }

    @Override
    protected Integer protected_getRequestedCount(String key) {
        return (Integer) this.cache.get(key);
    }

    @Override
    protected void protected_setRequestedCount(String key, int requestedCount, long expiration) {
        this.cache.put(key, requestedCount, expiration, Timeunit.MILL);
    }

    @Override
    protected void protected_removeRequestedCountEntry(String key) {
        this.cache.remove(key);
    }

    @Override
    protected long protected_getRemainder(String key) {
        return this.cache.getExpectedExpiration(key);
    }
}
